#include "reactor.h"
#include "selector.h"
#include "event.h"

SocketReactor::SocketReactor(SocketMGR* mgr)
    : _sock_mgr(mgr)
{
    _selector = SelectorFactory::Create(0);
}

void SocketReactor::Run()
{
    do
    {
        auto keys = _selector->SelectedKeys();

        Dispatch(keys);
    } while (true);
}

void SocketReactor::Regist(Event* e)
{
    _events.insert(std::make_pair(e->Id(), e));
    _selector->Insert(e->Id());
}

void SocketReactor::Dispatch(const std::set<int> &keys)
{
    for(auto it = keys.begin();
        it != keys.end();
        ++it)
    {
        _events[*it]->Handle();
    }
}
